<?php

namespace Apps\AppApi\Method\User;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\Keyword;
use Apps\Common\Models\UserBase;
use Apps\Common\Models\UserFollow;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\SysAreaZipDistrictPhonecode;
use PhalconPlus\Common\Util;
use Apps\Common\Libs\SmaUtil;


/**
 * 登录
 * @package Apps\AppApi\Method\User
 */
class Login extends BaseMethod
{
    /**
     * @var string
     */
    private $message = '';
    /**
     * @var \Apps\Common\Models\UserBase
     */
    private $userInfo = [];
    /**
     * @var int
     */
    private $success = 0;
    /**
     * @var string
     */
    private $userToken = '';
    

    public function run()
    {
        $account = $this->getDataItem('account'); // 验证电话号码格式
        $password = $this->getDataItem('password');
        $pushId = $this->getDataItem('push_id', '');// push id
        $osType = $this->getDataItem('os_type');

//        $account = '18723568682';
//        $password = '123456';
        // 验证数据完整
        if(empty($account) || empty($password)) {
            $this->message = '账户名和密码都不能为空!';
        } else {
            if ($this->verifyAccount($account, $password)) {
                // 获取 user token
                if ($this->saveuserauth($this->apiAccessToken->id, $this->userInfo['user_id'])) {
                    $this->success = 1;
                    $this->message = '登录成功!';
                    $this->userToken = $this->getUserAuth()->userToken;
                    $this->saveUserPushId($this->userInfo['user_id'], $pushId, $osType);

                    $this->userInfo['user_mobile'] = $this->userInfo['bind_phone'] ?: $this->userInfo['user_account'];
                    $this->userInfo['user_cover'] = $this->userInfo['user_cover'] ? PicUrl::UserCover($this->userInfo['user_cover'], $this->getDi()) : '';
                    $this->userInfo['persional_sign'] = $this->userInfo['persional_sign'] ? unserialize(base64_decode($this->userInfo['persional_sign'])) : '';

                    // 获取城市信息
                    $SysAreaZipDistrictPhonecode = new SysAreaZipDistrictPhonecode();
                    $city = $SysAreaZipDistrictPhonecode->getOne($this->userInfo['user_district']);
                    $this->userInfo['user_district'] = $city['FULL_NAME'] ?: '';

                    // 加入关注数和粉丝数
                    $UserFollow = new UserFollow();
                    $this->userInfo['follow_count'] = $UserFollow->getFollowCount($this->userInfo['user_id'], 1);

                    if ($this->userInfo['user_expert']) {
                        $this->userInfo['fans_count'] = $this->userInfo['expert_follow_count'];
                    } else {
                        $this->userInfo['fans_count'] = $UserFollow->getToFollowCount($this->userInfo['user_id'], 1);
                    }

                    //获取用户账号
                    $userid = $this->getUserAuth()->userId;
                    $mobile = UserBase::findFirst("user_id = {$userid}")->user_account;
                    $smautil = new SmaUtil();
                    $rs = $smautil->getIdentity($mobile);
                    //加入身份
                    if ($rs){
                        switch ($rs['type']){
                            case 1:
                            case 2:
                                $this->userInfo['identity'] = 3;
                                break;
                            case 3:
                                $this->userInfo['identity'] = 1;
                                break;
                            case 4:
                                $this->userInfo['identity'] = 2;
                                break;
                            default:
                                $this->userInfo['identity'] = 3;
                                break;
                        }
                    }
                    else {
                        $this->userInfo['identity'] = 3;//普通用户
                    }
                    // 删除不要的字段
                    unset($this->userInfo['user_account'], $this->userInfo['user_password'], $this->userInfo['user_state'], $this->userInfo['user_addtime'], $this->userInfo['is_manage'],  $this->userInfo['bind_phone']);
                } else {
                    $this->message = '获取User Token异常!';
                }
            }
        }
        if (!$this->userInfo) { // 登录失败依然保留字段
            $this->userInfo = [
                "user_id" => "",
                "user_nickname" => "",
                "user_mobile" => "",
                "user_cover" => "",
                "user_gender" => "0",
                "user_birthday" => "",
                "user_realname" => "",
                "user_expert" => "",
                "user_district" => "",
                "user_money" => "",
                "user_money_virtual" => "",
                "persional_sign" => "",
                "follow_count" => 0,
                "fans_count" => 0,
            ];
        }
        $info = [
            'success' => $this->success,
            'user_token' => $this->userToken,
            'message' => $this->message,
        ];
        $info = array_merge($info, $this->userInfo);

        $this->setResult($info);
    }

    /**
     * 验证用户账号和密码
     * @param string $account
     * @param string $password
     * @return bool
     */
    
    private function verifyAccount($account, $password)
    {
        //根据账号查询用户是否存在
        if ($model = UserBase::query()->where("user_account='{$account}'")->execute()->getFirst()) {
            $this->userInfo = $model->toArray();
        }

        if($this -> userInfo){//账户存在
            if($this -> userInfo['user_state'] != 1){//账户已被停用
                $this -> success = 3;
                $this->userInfo = [];
                $this->message = '账户已被停用，请联系管理员!';
                return false;
            }elseif($this -> userInfo['user_password'] != $this->hashPassword($password)){//密码错误
                $this -> success = 4;
                $this->userInfo = [];
                $this->message = '密码不正确!';
                return false;
            }

        } else { //未注册
            $this -> success = 2;
            $this->message = '账户未注册!';
            return false;
        }
        return true;
    }
   
    
}